package com.zjp.mg.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.javafaker.Faker;
import com.zjp.mg.dao.AbstractMongoService;
import com.zjp.mg.model.Garage;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.stereotype.Service;

import java.util.*;

// 位置
@Service
public class GarageService extends AbstractMongoService<Garage> {
    @Override
    public String getCollectionName() {
        return "garage";
    }

    @Override
    public Class<Garage> getType() {
        return Garage.class;
    }

    public List<Garage> getGarage(Integer page) {
        String APP_KEY = StrUtil.EMPTY;

        String url = "https://restapi.amap.com/v3/place/text?parameters";

        Faker faker = Faker.instance(Locale.CHINA);

        String city = faker.address().city();

        Map<String, Object> map = new HashMap<>();

        map.put("key", APP_KEY);
        map.put("keywords", "停车场");
        map.put("city", city);
        map.put("page", page);

        String s = HttpUtil.get(url, map);


        JSONObject object = JSONUtil.parseObj(s);


        System.out.println(JSONUtil.toJsonPrettyStr(s));

        JSONArray pois = object.getJSONArray("pois");

        if (CollUtil.isEmpty(pois)) {
            return null;
        }
        List<Garage> list = new ArrayList<>();
        for (Object o : pois) {
            JSONObject entries = JSONUtil.parseObj(o);
            Garage garage = new Garage();
            garage.setGarageName(entries.getStr("name"));
            garage.setAddress(entries.getStr("address"));
            String location = entries.getStr("location");
            List<String> split = StrUtil.split(location, StrUtil.COMMA);
            GeoJsonPoint geoJsonPoint = new GeoJsonPoint(Double.parseDouble(split.get(0)), Double.parseDouble(split.get(1)));
            garage.setLocation(geoJsonPoint);
            list.add(garage);
        }
        return list;
    }

    public Garage insertByAutoId(Garage garage) {
        garage.setGarageId(getNextAutoId());
        return insert(garage);
    }
}
